#!/usr/bin/python2.4

import codecs
import sys


def main():
  if len(sys.argv) < 2:
    print 'Usage: %s <input file> [output file]' % (sys.argv[0])
    sys.exit(1)

  input_file = codecs.open(sys.argv[1], 'r', 'utf-16')
  output_file = sys.stdout
  if len(sys.argv) > 2:
    output_file = codecs.open(sys.argv[2], 'w', 'utf-16')

  previous_data = ''
  for line in input_file:
    cells = line.split('\t')
    if len(cells) > 1:
      previous_data = '\t'.join(cells[0:-1])
      cells[-1] = cells[-1].replace('""', '"').rstrip('"\n')
      if cells[-1].count('"') % 2 and cells[-1][0] == '"':
        cells[-1] = cells[-1][1:]
      output_file.write('\t'.join(cells) + '\n')
    else:
      line = line.replace('""', '"').rstrip('"\n') + '\n'
      output_file.write('%s\t%s' % (previous_data, line))

  output_file.close()

if __name__ == '__main__':
  main()

